package com.shorturi.uri.controller;

import com.robert.vesta.service.intf.IdService;
import com.shorturi.uri.JsonResopnse;
import com.shorturi.uri.domains.UriEntity;
import com.shorturi.uri.repository.UriRepository;
import com.shorturi.uri.service.UriService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.elasticsearch.core.ElasticsearchOperations;
import org.springframework.data.elasticsearch.core.ElasticsearchTemplate;
import org.springframework.data.elasticsearch.core.query.Criteria;
import org.springframework.data.elasticsearch.core.query.CriteriaQuery;
import org.springframework.stereotype.Controller;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.*;

import javax.validation.constraints.NotNull;

/**
 * @author sola
 */
@Controller
@Slf4j
public class UriController {

    private UriRepository uriRepository;

    private ElasticsearchOperations operations;

    private ElasticsearchTemplate elasticsearchTemplate;

    private IdService idService;

    private UriService uriService;

    @Value("${path.value}")
    @NotNull
    private String pathValue;

    @Autowired
    public UriController(UriRepository uriRepository, ElasticsearchOperations operations, ElasticsearchTemplate elasticsearchTemplate, IdService idService, UriService uriService) {
        this.uriRepository = uriRepository;
        this.operations = operations;
        this.elasticsearchTemplate = elasticsearchTemplate;
        this.idService = idService;
        this.uriService = uriService;
    }

    @PostMapping(value = "/get_long_uri")
    @ResponseBody
    public JsonResopnse saveShortUri(@RequestBody UriEntity uriEntity) {
        JsonResopnse.JsonResopnseBuilder builder = JsonResopnse.builder();
        Assert.notNull(uriEntity.getLongUri(), "notNull");
        final Long id = idService.genId();
        final String ipAddress = uriService.getIpAddress();
        uriEntity.setId(id);
        uriEntity.setLongUri(uriEntity.getLongUri());
        uriEntity.setShortUri(ipAddress + id);
        uriRepository.save(uriEntity);
        return builder.success("true").message(ipAddress + id.toString()).code(id.toString()).build();
    }

    @GetMapping(value = "/s/{id}")
    public String getLongUri(@PathVariable("id") String id) {
        CriteriaQuery criteriaQuery = new CriteriaQuery(new Criteria("_all")
                .and(new Criteria("shortUri").endsWith(id)));
        UriEntity uriEntity = elasticsearchTemplate.queryForObject(criteriaQuery, UriEntity.class);
        if (uriEntity != null) {
            return "redirect:" + uriEntity.getLongUri();
        } else {
            return "redirect:/";
        }
    }


}
